import os
import time
import subprocess
import signal

log_file = "output.log"
timeout = 30  
check_interval = 5 
command = "nohup python inference.py > output.log 2>&1 &"

def get_file_modification_time(file_path):
    try:
        return os.path.getmtime(file_path)
    except FileNotFoundError:
        return None

def start_process():
    return subprocess.Popen(command , 
                            shell=True, 
                            preexec_fn=os.setsid)

def terminate_process(process):
    os.killpg(os.getpgid(process.pid), signal.SIGTERM)

def main():
    process = start_process()
    last_modification_time = get_file_modification_time(log_file)
    last_checked_time = time.time()

    try:
        while True:
            time.sleep(check_interval)
            current_modification_time = get_file_modification_time(log_file)
            if current_modification_time != last_modification_time:
                last_modification_time = current_modification_time
                last_checked_time = time.time()
            elif time.time() - last_checked_time > timeout:
                print("Log file has not updated for a while. Restarting process...")
                terminate_process(process)
                process = start_process()
                last_checked_time = time.time()
    except KeyboardInterrupt:
        print("Stopping the monitor...")
    finally:
        terminate_process(process)

if __name__ == "__main__":
    main()
